/**
 * URLSearchParams Polyfill for WeChat Mini Program
 * 微信小程序环境下的 URLSearchParams 替代方案
 * 
 * 使用方法：
 * import { URLSearchParamsPolyfill } from '@/utils/url-search-params-polyfill'
 * const params = new URLSearchParamsPolyfill({ key: 'value' })
 * console.log(params.toString()) // 'key=value'
 */

export class URLSearchParamsPolyfill {
  constructor(init) {
    this.params = new Map()
    
    if (init) {
      if (typeof init === 'string') {
        this.parseString(init)
      } else if (typeof init === 'object') {
        this.parseObject(init)
      }
    }
  }
  
  parseString(str) {
    // 移除开头的 ? 号（如果有）
    const cleanStr = str.startsWith('?') ? str.slice(1) : str
    
    if (!cleanStr) return
    
    const pairs = cleanStr.split('&')
    for (const pair of pairs) {
      const [key, value = ''] = pair.split('=')
      if (key) {
        this.append(decodeURIComponent(key), decodeURIComponent(value))
      }
    }
  }
  
  parseObject(obj) {
    for (const [key, value] of Object.entries(obj)) {
      this.set(key, value)
    }
  }
  
  append(name, value) {
    const key = String(name)
    const val = String(value)
    
    if (this.params.has(key)) {
      const existing = this.params.get(key)
      if (Array.isArray(existing)) {
        existing.push(val)
      } else {
        this.params.set(key, [existing, val])
      }
    } else {
      this.params.set(key, val)
    }
  }
  
  delete(name) {
    this.params.delete(String(name))
  }
  
  get(name) {
    const value = this.params.get(String(name))
    if (Array.isArray(value)) {
      return value[0]
    }
    return value || null
  }
  
  getAll(name) {
    const value = this.params.get(String(name))
    if (Array.isArray(value)) {
      return [...value]
    }
    return value ? [value] : []
  }
  
  has(name) {
    return this.params.has(String(name))
  }
  
  set(name, value) {
    this.params.set(String(name), String(value))
  }
  
  toString() {
    const result = []
    
    for (const [key, value] of this.params.entries()) {
      if (Array.isArray(value)) {
        for (const val of value) {
          result.push(`${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
        }
      } else {
        result.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      }
    }
    
    return result.join('&')
  }
  
  // 迭代器支持
  *entries() {
    for (const [key, value] of this.params.entries()) {
      if (Array.isArray(value)) {
        for (const val of value) {
          yield [key, val]
        }
      } else {
        yield [key, value]
      }
    }
  }
  
  *keys() {
    for (const [key] of this.entries()) {
      yield key
    }
  }
  
  *values() {
    for (const [, value] of this.entries()) {
      yield value
    }
  }
  
  forEach(callback, thisArg) {
    for (const [key, value] of this.entries()) {
      callback.call(thisArg, value, key, this)
    }
  }
}

/**
 * 检测是否支持原生 URLSearchParams
 */
export function isURLSearchParamsSupported() {
  try {
    return typeof URLSearchParams !== 'undefined' && 
           typeof URLSearchParams.prototype.toString === 'function'
  } catch (e) {
    return false
  }
}

/**
 * 获取适合当前环境的 URLSearchParams 构造函数
 * 在微信小程序等不支持原生 URLSearchParams 的环境中，返回 polyfill 版本
 */
export function getURLSearchParams() {
  if (isURLSearchParamsSupported()) {
    return URLSearchParams
  }
  return URLSearchParamsPolyfill
}

/**
 * 便捷的工具函数：将对象转换为查询字符串
 * @param {Object} obj - 要转换的对象
 * @returns {string} 查询字符串（不包含前导 ?）
 */
export function objectToQueryString(obj) {
  if (!obj || typeof obj !== 'object') {
    return ''
  }
  
  const URLSearchParamsClass = getURLSearchParams()
  const params = new URLSearchParamsClass(obj)
  return params.toString()
}

/**
 * 便捷的工具函数：将查询字符串转换为对象
 * @param {string} queryString - 查询字符串（可以包含前导 ?）
 * @returns {Object} 转换后的对象
 */
export function queryStringToObject(queryString) {
  if (!queryString || typeof queryString !== 'string') {
    return {}
  }
  
  const URLSearchParamsClass = getURLSearchParams()
  const params = new URLSearchParamsClass(queryString)
  const result = {}
  
  for (const [key, value] of params.entries()) {
    if (result[key]) {
      // 如果已存在该键，转换为数组
      if (Array.isArray(result[key])) {
        result[key].push(value)
      } else {
        result[key] = [result[key], value]
      }
    } else {
      result[key] = value
    }
  }
  
  return result
}

// 默认导出
export default {
  URLSearchParamsPolyfill,
  isURLSearchParamsSupported,
  getURLSearchParams,
  objectToQueryString,
  queryStringToObject
}